package util;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @description: 数据库连接工具类
 * @author: chengbaiyi
 * @create: 2022-06-25 17:11
 */
public class DBUtil {
    private DBUtil() {}

    private static volatile MysqlDataSource dataSource;

    private static MysqlDataSource getDataSource() {
        if (dataSource == null) {
            synchronized (DBUtil.class) {
                if (dataSource == null) {
                    dataSource = new MysqlDataSource();
                    // dataSource.setURL("jdbc:mysql://127.0.0.1:3306/orderdb2022?characterEncoding=utf8&useSSL=true");
                    dataSource.setURL("jdbc:mysql://127.0.0.1:3306/orderdb2022?characterEncoding=utf8&useSSL=false");
                    dataSource.setUser("root");
                    dataSource.setPassword("12345678");
                }
            }
        }
        return dataSource;
    }

    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }

    // 关闭资源
    public static void close(ResultSet resultSet, PreparedStatement statement, Connection connection) throws SQLException {
        if (resultSet != null) resultSet.close();
        if (statement != null) statement.close();
        if (connection != null) connection.close();
    }
}
